<template>
  <div>
    <van-nav-bar  z-index="999" title="城市列表" left-arrow @click-left="$router.back()" class="nav"></van-nav-bar>
    <div class="list">
      <van-index-bar :index-list="indexList" :sticky-offset-top = num>
        <van-index-anchor :index='item' v-for="(item,index) in indexList" :key="index">
          <p>{{fenlei[index]}}</p><van-cell @click="homeCityFn(item1)"  :title="item1.label" v-for="item1 in list.filter(item2=>item2.j===item)" :key="item1.id" />
        </van-index-anchor>
      </van-index-bar>
    </div>
  </div>
</template>

<script>
import { cityList, cityHot, getFangyuan } from '@/api/city'

export default {
  name: 'CityList',
  data () {
    return {
      indexList: [],
      list: [],
      hot: [],
      num: 50,
      cityInfo: '',
      fenlei: ['当前城市', '热门城市']
    }
  },
  async created () {
    const resList = await cityList()
    const resHot = await cityHot()
    this.list = resList.body
    this.hot = resHot.body
    this.list.sort((a, b) => {
      return a.short.localeCompare(b.short)
    })
    this.hot.sort((a, b) => {
      return a.short.localeCompare(b.short)
    })
    // 增加类名j
    this.hot.forEach(item => { item.j = '热' })
    this.list.forEach(item => { item.j = item.short[0].toUpperCase() })
    // 处理城市数据
    this.list = [...this.list, ...this.hot, { ...JSON.parse(localStorage.getItem('cityInfo')) }]
    console.log(this.list)
    // 处理索引数据
    const suoyin = this.list.map(i => i.short[0].toUpperCase())
    this.indexList = [...Array.from(new Set(suoyin))]
    // 分类标识
    this.fenlei.push(...this.indexList)
    // console.log(this.fenlei)
    // 增加索引，去重
    this.indexList.unshift('#', '热')
    this.indexList = Array.from(new Set(this.indexList))
  },
  methods: {
    async homeCityFn (item1) {
      const res = await getFangyuan(item1.label)
      if (res.body.label !== '上海' || item1.label === '上海') {
        item1.j = '#'
        localStorage.setItem('cityInfo', JSON.stringify(item1))
        this.$router.back()
      } else {
        this.$toast('该城市暂无房源')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.nav{
position: sticky;
top: 0;
}
p{
  margin: 0;
  padding: 0;
  font-size: 14px;
  color: #999;
  margin-left: 10px;
}
.hot{
  margin-left: 10px;
}
/deep/ .van-index-bar__index--active{
  color: #fff;
    background-color: #21b97a;
    border-radius: 100%;
    display: inline-block;
    font-size: 12px;
    width: 15px;
    height: 15px;
    line-height: 15px;
}
/deep/ .van-index-bar__index{
    margin: 0 10px;
    padding: 0;
}
</style>
